package com.exercises;

//缺失的第一个正数
class Exercise17_21 {
    public static void main(String[] args) {
        System.out.println(trap(new int[]{4, 9, 4, 5, 3, 2}));
    }

    public static int trap(int[] height) {
        int sum = 0;
        for (int i = 0; i < height.length; ) {
            if (height[i] == 0) {
                i++;
                continue;
            } else {
                int cursor = i + 1;
                int j = cursor;
                int max = 0;
                while (cursor < height.length) {
                    if (height[cursor] >= max) {
                        max = height[cursor];
                        j = cursor;
                    }
                    if (max >= height[i]) {
                        break;
                    }
                    cursor++;
                }
                if (max == 0) {
                    break;
                } else {
                    int l = Math.min(height[i], height[j]);
                    for (int k = i + 1; k < j; k++) {
                        if (height[k] < l) {
                            sum += (l - height[k]);
                        }
                    }
                    i = j;
                }

            }
        }
        return sum;

    }


}
